package file;

import java.io.IOException;
import java.io.RandomAccessFile;

public class Tailing {
    public static void main(String[] args) throws IOException {
        System.out.println(tail("D:/a.txt", 12));
    }

    public static String tail(String file, int n) throws IOException {
        RandomAccessFile accessFile = new RandomAccessFile(file, "r");
        long total = accessFile.length();
        int bath = 128;
        int curN = 0;
        StringBuilder result = new StringBuilder();
        long pos = total - 1;
        while (curN < n && pos > 0) {
            byte[] bytes = new byte[bath];
            pos = pos - bath;
            pos = pos < 0 ? 0 : pos;
            accessFile.seek(pos);
            accessFile.read(bytes, 0, bath);

            String lines = new String(bytes, "UTF-8");
            String[] split = lines.split("\n");
            if (!lines.endsWith("\n") && curN > 0) {
                curN--;
            }
            int accept = n - curN;
            int length = split.length;
            if (accept < length) {
                for (int i = length - 1; i >= length - accept; i--) {
                    if (i < length - 1) {
                        result.insert(0, "\n");
                    }
                    result.insert(0, split[i]);
                }
                curN = n;
            } else {
                curN += split.length;
                result.insert(0, lines);
            }
        }

        try {
            accessFile.close();
        } catch (Exception ignore) {

        }

        return result.toString();
    }
}
